<?php
declare (strict_types=1);

namespace app\middleware;

use app\services\user\AdminUserService;
use app\services\utils\TokenService;


class Auth
{

    /**
     * 认证中间件
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next)
    {
        try {
            $token = $request->header('token');
            if (empty($token)) {
                throw new \Exception('请重新登录', -1);
            }
            $result = (new TokenService())->checkToken($token);
            if ($result->exp < time()) {
                throw new \Exception('请重新登录', -1);
            }
            $tokenInfo = $result->data;
            $userId = $tokenInfo->id;
            $userInfo = AdminUserService::getUserInfo($userId);
            if ($tokenInfo->username != $userInfo['username']) {
                throw new \Exception('请重新登录', -1);
            }
            $request->userId = $userId;
            $request->userInfo = $userInfo;
        } catch (\Exception $exception) {
            return json()->data(['code' => $exception->getCode(), 'msg' => $exception->getMessage(), 'data' => []]);
        }
        return $next($request);
    }
}
